package com.lazason.xingming;

import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		TextView result = (TextView) findViewById(R.id.result);
		result.setText("" + getNameCounter("李明"));

	}

	@Override
	public View findViewById(int id) {
		// TODO Auto-generated method stub
		return super.findViewById(id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	private String getNameCounter(String name) {
		String url = null;
		try {
			url = new String("http://name.renren.com/xingming/search?q="
					+ URLEncoder.encode(name, "utf8"));
			Log.d("xingming",url);
			System.out.println(url);
			Document doc = Jsoup.connect(url).get();
			Elements namesakers = doc.getElementsByTag("h2");
		 
			  String regEx = "[^0-9]";
		        Pattern p = Pattern.compile(regEx);
		        Matcher m = p.matcher(namesakers.html());
		        return m.replaceAll("").trim(); 
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
}
